/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.hyk.appcfg.wrapper.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author qiying.wang
 */
public class SimpleTextFileModifier {

    public static void modify(String file, String tagName, String newValue) throws FileNotFoundException, IOException {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String patternStr = "^[\\s]*" + tagName + ":[^\r\n]*";
        Pattern p = Pattern.compile(".*(" + patternStr + ").*");

        String line = reader.readLine();
        StringBuffer newFileContent = new StringBuffer();
        while (line != null) {
            Matcher m = p.matcher(line);
            if (m.matches()) {
                String target = m.group(1);
                String newContent = line.replace(target, tagName + ": " + newValue);
                newFileContent.append(newContent).append("\n");
            } else {
                newFileContent.append(line).append("\n");
            }
            line = reader.readLine();
        }
        FileWriter writer = new FileWriter(file);
        writer.write(newFileContent.toString());
        writer.close();
    }
}
